package com.hnucm.cooklife.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Animatable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.graphics.ColorUtils;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat;

import com.hnucm.cooklife.R;
import com.hnucm.cooklife.adapter.SearchHistoryAdapter;
import com.hnucm.cooklife.base.BaseActivity;
import com.hnucm.cooklife.base.Utils;
import com.hnucm.cooklife.base.utils.Constant;
import com.hnucm.cooklife.base.utils.KeyBoardUtils;
import com.hnucm.cooklife.bean.search.SearchData;
import com.hnucm.cooklife.contract.searchword.Contract;
import com.hnucm.cooklife.presenter.searchwords.SearchWordPresenter;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchWordActivity extends BaseActivity<Contract.ISearchWordView, SearchWordPresenter> implements Contract.ISearchWordView {
    @BindView(R.id.search_edit)
    EditText mSearchEdit;

    @BindView(R.id.search_text_top)
    TextView mTopSearchWord;

    @BindView(R.id.search_text_history)
    TextView mSearchHistory;

    @BindView(R.id.search_clear)
    TextView mSearchClear;

    @BindView(R.id.search_recycler)
    RecyclerView mRecyclerView;

    @BindView(R.id.search_flowlayout)
    TagFlowLayout mTopSearchFlowLayout;

    @BindView(R.id.anim_img)
    ImageView mSearchAnimImage;

    private Context mContext;
    private List<String> mSearchHistoryList = new ArrayList<>();
    private SearchHistoryAdapter mSearchHistoryAdapter;


    @OnClick(R.id.search_clear)
    void onClick(View view){
        switch (view.getId()){
            case R.id.search_clear:
                clearHistoryData();
                break;
            default:
                break;
        }
    }

    private void clearHistoryData() {
        mSearchClear.setVisibility(View.GONE);
        mSearchHistory.setVisibility(View.GONE);
        Utils.deleteAllSearchHistory(mContext);
        mSearchHistoryList.clear();
        mSearchHistoryList = Utils.getAllSearchHistory(mContext);
        mSearchHistoryAdapter.setSearchHistoryList(mSearchHistoryList);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_searchword;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mContext = getApplicationContext();
        initStatusBar();
        initSearchEdit();
        initCircleAnimation();
        initAdapter();
        if(Utils.getAllSearchHistory(mContext).size() != 0){
            mSearchHistory.setVisibility(View.VISIBLE);
            mSearchClear.setVisibility(View.VISIBLE);
        }
        mPresenter.loadSearchWordData();
    }
    private void initStatusBar() {
        getWindow().setStatusBarColor(Utils.getColor(mContext));
        if (ColorUtils.calculateLuminance(Utils.getColor(mContext)) >= 0.5) {
            // 设置状态栏中字体的颜色为黑色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            // 跟随系统
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }


    private void initSearchEdit() {
        //将焦点放到ImageView上
        mSearchAnimImage.setFocusable(true);
        mSearchAnimImage.setFocusableInTouchMode(true);
        mSearchAnimImage.requestFocus();
        mSearchAnimImage.requestFocusFromTouch();
        mSearchEdit.setOnFocusChangeListener((v,hasFocus) ->{
            if(hasFocus){
                AnimatedVectorDrawableCompat animatedVectorDrawableCompat = AnimatedVectorDrawableCompat.create(
                        SearchWordActivity.this, R.drawable.animated_vector_search
                );
                mSearchAnimImage.setImageDrawable(animatedVectorDrawableCompat);
                if(TextUtils.isEmpty(mSearchEdit.getText())){
                    ((Animatable) mSearchAnimImage.getDrawable()).start();
                }
            }
        });

        // 将软键盘的回车搜索启用
        mSearchEdit.setOnEditorActionListener((v, actionId, event) -> {
            KeyBoardUtils.closeKeyboard(mContext, this);
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                handleSearchAction();
            }
            return false;
        });

        mSearchAnimImage.setOnClickListener(v -> {
            KeyBoardUtils.closeKeyboard(mContext, this);
            handleSearchAction();
        });
    }


    //添加历史记录并跳珠转到搜索结果页
    private void handleSearchAction() {
        if(!TextUtils.isEmpty(mSearchEdit.getText())){
            mSearchClear.setVisibility(View.VISIBLE);
            mSearchHistory.setVisibility(View.VISIBLE);
            Utils.setSearchHistory(mSearchEdit.getText().toString(),mContext);
            mSearchHistoryAdapter.setSearchHistoryList(Utils.getAllSearchHistory(mContext));

            //跳转到搜索结果页
            Intent intent = new Intent(SearchWordActivity.this, DishResultActivity.class);
            intent.putExtra(Constant.KEY_KEYWORD,mSearchEdit.getText().toString());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    private void initCircleAnimation() {
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
        mSearchHistoryList.addAll(Utils.getAllSearchHistory(mContext));
        mSearchHistoryAdapter = new SearchHistoryAdapter(mContext,mSearchHistoryList);
        mRecyclerView.setAdapter(mSearchHistoryAdapter);
    }

    @Override
    protected SearchWordPresenter createPresenter() {
        return new SearchWordPresenter();
    }

    @Override
    public void onloadSearhWord(SearchData searchData) {
        List<String> tabNames = searchData.getData().stream().map(SearchData.DataDTO::getHname)
                .collect(Collectors.toList());
        mTopSearchFlowLayout.setAdapter(new TagAdapter(tabNames) {
            @Override
            public View getView(FlowLayout parent, int position, Object o) {
                TextView tagText = (TextView) LayoutInflater.from(SearchWordActivity.this).inflate(R.layout.flow_layout, parent, false);
                tagText.setText(tabNames.get(position));
                tagText.getBackground().setColorFilter(Utils.randomColor(), PorterDuff.Mode.SRC_ATOP);
                //点击了热门搜索后就会更新历史搜索
                mTopSearchFlowLayout.setOnTagClickListener(((view, position1, parent1) -> {
                    Utils.setSearchHistory(tabNames.get(position1),mContext);
                    mSearchClear.setVisibility(View.VISIBLE);
                    mSearchHistory.setVisibility(View.VISIBLE);
                    mSearchHistoryAdapter.setSearchHistoryList(Utils.getAllSearchHistory(mContext));
                    Intent intent = new Intent(SearchWordActivity.this, DishResultActivity.class);
                    intent.putExtra(Constant.KEY_KEYWORD,tabNames.get(position1));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    return true;
                }));
                return tagText;
            }
        });
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoadingFailed() {

    }

    @Override
    public void onLoadSuccess() {

    }
}
